<template>
  <div class="comment-view">
    <u-comment :config="config" :show-size="1" @submit="submit" @remove="remove" @report="report">
    </u-comment>
  </div>
</template>

<script setup lang="ts">
import { reactive, inject, ref } from 'vue'
import {
  UToast,
  ConfigApi,
  CommentApi,
  CommentSubmitParam,
} from 'undraw-ui'
import emoji from '@/utils/emoji/emoji'
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import dayjs from 'dayjs'
import { postComment, findComment, delAllComment, reportComment } from '@/utils/http/comment'
// 引入全局状态
const store: any = inject('store')

// 引入的地图的api
const BMap = (window as any).BMap
// 地理位置
const address = ref<string>('未获取到地址')
const config = reactive<ConfigApi>({
  user: {
    id: store.state.userBase._id,
    username: store.state.userBase.username || '未获取到',
    avatar:
      store.state.userBase.avatar ? store.state.BaseUrl + store.state.userBase.avatar :
        'https://static.juzicon.com/avatars/avatar-200602130320-HMR2.jpeg?x-oss-process=image/resize,w_100',
    likeIds: [],
  },
  emoji: emoji,
  comments: [],
})

// 提交评论事件
const router = useRouter()
const route = useRoute()
const props = defineProps<{
  articleTitle: string
}>()
// 提交函数
const submit = async ({
  content,
  parentId,
  files,
  finish,
}: CommentSubmitParam) => {
  if (!store.state.userBase.username) {
    ElMessage.error('请登录')
    router.push('/login')
    return
  }
  // 提交
  let { data } = await postComment(
    parentId,
    String(config.user.id),
    address.value,
    content,
    route.query.id as string,
    props.articleTitle,
    config.user.username,
    config.user.avatar,
    '1'
  )

  // 类型
  let comment: CommentApi = {
    id: data.data._id,
    parentId: parentId,
    uid: data.data.uid,
    address: data.data.address,
    content: content,
    likes: 0,
    createTime: dayjs(data.data.createTime).format('YYYY-MM-DD/HH:mm'),
    contentImg: '',
    user: {
      username: config.user.username,
      avatar: config.user.avatar,
      level: 6,
      homeLink: `javascript:;`,
    },
    reply: null,
  }
  finish(comment)
  UToast({ message: '评论成功!', type: 'info' })
}

// 删除评论
const remove = async (id: string, finish: () => void) => {
  let arr = config.comments.filter(item => item.id == id)[0] || { reply: { list: [] } }
  let hasChildComment = arr.reply || { list: [] }
  let ids: string[] = []
  if (hasChildComment.list.length) {
    ids = [...hasChildComment.list.map(item => item.id) as string[], id]
  } else {
    console.log(id);
    ids = [id]
  }

  ids.length && delAllComment(ids).then(res => {
    console.log(res.data);
    res.data.data.deletedCount > 0 && finish()
  })

}

//举报用户
const report = async (id: string, finish: () => void) => {
  await reportComment(id)
  UToast({ message: '您对他的举报成功等待管理员处理!', type: 'success' })
}

// 获取评论
const getComment = () => {
  route.query.id &&
    findComment(route.query.id as string).then((res) => {
      let baseArr = res.data.info as any
      let hasParentId: any[] = []
      let notHasParentId = []
      for (let i = 0; i < baseArr.length; i++) {
        let item = {
          ...baseArr[i],
          id: baseArr[i]._id,
          createTime: dayjs(baseArr[i].createTime).format('YYYY-MM-DD/HH:mm'),
          homeLink: `javascript:;`,
          childFlag: false,
          reply: { total: 0, list: [] },
        }
        if (item.parentId) {
          hasParentId.push(item)
        } else {
          notHasParentId.push(item)
        }
      }
      config.comments = notHasParentId.map(item => {
        for (let j = 0; j < hasParentId.length; j++) {
          if (item.id == hasParentId[j].parentId) {
            hasParentId[j].childFlag = true
            item.reply.total++
            item.reply.list.push(hasParentId[j])
          }
        }
        return item
      })

    })

}
getComment()

// 获取地理位置
let addr = new BMap.Geolocation()
addr.getCurrentPosition(function (r: any) {
  address.value = r.address.province + r.address.city
})
</script>

<style lang="scss">
.comment-view {
  a {
    pointer-events: none;
    cursor: default !important;
  }

  .time {
    padding-right: 5px;
  }

  .reply-box .reply-list {
    padding-right: 0;
  }
}

.username {
  .rank {
    display: none;
  }
}

.u-comment {
  padding: 0 !important;

  .item:nth-child(1) {
    display: none;
  }

  .picture {
    display: none;
  }

  .content {
    height: auto !important;
  }
}

.vp-doc ul {
  list-style: none !important;
}

.vp-doc ul,
.vp-doc ol {
  padding-left: 0 !important;
  margin: 0 !important;
}

.vp-doc li+li {
  margin-top: 0px !important;
}

@media (max-width: 760px) {
  .user-box {

    .time {
      font-size: 12px !important;

    }
  }

  .reply-list {
    padding: 10px 5px !important;
  }
}
</style>
